package org.giovanolli.mumi.dao.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.giovanolli.mumi.dao.PatientDao;
import org.giovanolli.mumi.entities.Patient;
import org.giovanolli.mumi.entities.filter.EntityFilter;
import org.giovanolli.mumi.entities.filter.PatientFilter;
import org.giovanolli.mumi.entities.filter.SortCriteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * The Class PatientDaoImpl.
 */
@Repository("patientDao")
public class PatientDaoImpl extends HibernateDao<Patient> implements PatientDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.dao.impl.HibernateDao#fillCriteria(org.giovanolli .mumi.entities.filter.EntityFilter, org.hibernate.criterion.DetachedCriteria)
	 */
	@Override
	protected DetachedCriteria fillCriteria(EntityFilter<Patient> filter, DetachedCriteria criteria) {
		final PatientFilter entityFilter = (PatientFilter) filter;

		if (filter != null) {
			if (entityFilter.getFirstName() != null) {
				criteria.add(Restrictions.ilike("firstName", entityFilter.getFirstName(), MatchMode.ANYWHERE));
			}
			if (entityFilter.getFirstName() != null) {
				criteria.add(Restrictions.ilike("lastName", entityFilter.getLastName(), MatchMode.ANYWHERE));
			}
			if (entityFilter.getPrepaid() != null) {
				criteria.createAlias("prepaids", "prepaids").add(Restrictions.eq("prepaids.prepaid", entityFilter.getPrepaid()));
			}
			if (entityFilter.getSpecialist() != null) {
				criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
				criteria.createAlias("attentionTimes", "attentionTimes").createAlias("attentionTimes.specialistFee", "specialistFee")
				        .add(Restrictions.eq("specialistFee.specialist", entityFilter.getSpecialist()));
			}
			if (CollectionUtils.isNotEmpty(filter.getSortCriterias())) {
				for (SortCriteria sortCriteria : filter.getSortCriterias()) {
					criteria.addOrder(sortCriteria.getAsc() ? Order.asc(sortCriteria.getAttribute()) : Order.desc(sortCriteria.getAttribute()));
				}
			}

		}
		return criteria;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.dao.impl.HibernateDao#setDefaultSortCriteria(java.util.List)
	 */
	@Override
	protected void setDefaultSortCriteria(List<SortCriteria> defaultSortCriteria) {
		defaultSortCriteria.add(new SortCriteria("lastName", true));
		defaultSortCriteria.add(new SortCriteria("firstName", true));
	}
}
